package fregat.base.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ResourceBundle;

/**
 * The file parser reads all lines from a file and calls
 * {@link #parseLine(java.lang.String)} to interpret the line's data.
 *
 * @author Alexander Mann <br><b><i>ECO_L O G</i> &nbsp Logistiksysteme GmbH</b>
 * @version 1.0
 */
public abstract class FileParser {
  private String debug = "lines";
  private boolean shutdown;
  private static ResourceBundle resource = ResourceBundle.getBundle("at.ecolog.base.util.resource");

  /**
   * Should interpret the line's data and move it to a data structure.
   *
   * @param line Line read from file
   * @return True, if line was successfully interpreted
   */
  protected abstract boolean parseLine(String line);

  /**
   * Sets the debug text used for report how many lines have been read.
   *
   * @param debug Replaces 'lines' in debug summary.
   */
  public void setDebug(String debug) {
    this.debug = debug;
  }

  /**
   * Reads all lines from the given file.
   *
   * @param filename Full path to file
   */
  public void readFile(String filename) {
    if (filename == null) {
      Logger.getDefaultCategory().error("FileParser, " + resource.getString("FileParser_readFile_1"));
      return;
    }
    BufferedReader fileReader = null;
    int lineCount = 0;
    try {
      fileReader = new BufferedReader(new FileReader(new File(filename)));
      String line = null;
      while ((line = fileReader.readLine()) != null && !shutdown) {
        if (line.length() > 0 && line.charAt(0) != '#') {
          if (parseLine(line)) lineCount++;
        }
      }
      Logger.getDefaultCategory().note("FileParser, " + lineCount + " "
          + debug + " " +
          resource.getString("FileParser_readFile_3") +
          " " + filename);
    } catch (IOException ex) {
      Logger.getDefaultCategory().error("FileParser, " +
          resource.getString("FileParser_readFile_2") +
          " '" + filename + "'", ex);
    } finally {
      if (fileReader != null) {
        try {
          fileReader.close();
        } catch (Exception ex) {
        }
      }
    }
  }

  /**
   * Stops reading from the file.
   */
  public void shutdown() {
    shutdown = true;
  }
}
